package fanjingzhu.check.dao.impl;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import publics.model.Enterprise;
import publics.model.ProposerGuarantee;
import fanjingzhu.check.dao.ProposerGuaranteeDao;
@Component("proposerGuaranteeDao")
public class ProposerGuaranteeDaoImpl implements ProposerGuaranteeDao{
	
	HibernateTemplate hibernateTemplate;// hibernate的spring代理模版

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	// 注入 hibernate模版
	@Resource(name = "hibernateTemplate")	
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
		System.out.println("hibernateTemplate injected in proposerGuaranteeDaoImpl!");
		// 测试用，实际运行中可去掉这句
	}
	
	public Integer save(ProposerGuarantee guarantee) {
		return (Integer)this.getHibernateTemplate().save(guarantee);
	}

	public boolean delete(ProposerGuarantee guarantee) {
		try{ this.getHibernateTemplate().delete(guarantee);
		}catch(DataAccessException e){
			return false;
		}
		return true;
	}
	
	public boolean deleteById(Integer guaranteeId) {
		try{ this.getHibernateTemplate().delete(this.getHibernateTemplate().get(ProposerGuarantee.class, guaranteeId));
		}catch(DataAccessException e){
			return false;
		}
		return true;
	}
	
	public boolean update(ProposerGuarantee guarantee) {
		try{
			this.getHibernateTemplate().update(guarantee);
		}catch(DataAccessException e){
		    return false;
	      }
      return true;
    }

	public int findByCount(String sql) {
		return this.getHibernateTemplate().find(sql).size();
	}

	public ProposerGuarantee findById(Integer id) {
		return this.getHibernateTemplate().get(ProposerGuarantee.class, id);
	}
	@SuppressWarnings("unchecked")
	public List<ProposerGuarantee> findByPage(final String hql, final int offset,
			final int pageSize) {
		List<ProposerGuarantee> list = this.getHibernateTemplate().executeFind(
				new HibernateCallback() {
					public Object doInHibernate(Session session) throws HibernateException ,SQLException {
						//执行hibernate分页查询
						List<Enterprise> result = session.createQuery(hql)
						.setFirstResult(offset)
						.setMaxResults(pageSize)
						.list();
						return result;
					}
				}
				);
		
		return list;
	}	
}